import tkinter as tk
from tkinter import ttk, messagebox
from src.ui.tkinter.styles.colors import BACKGROUND_MAIN
from src.core.item_manager import create_item

def show_creation_screen(parent: tk.Tk, items: dict) -> None:
    """Clear the parent window and display the bread addition page"""
    for widget in parent.winfo_children():
        widget.destroy()

    title_label = ttk.Label(
        parent,
        text="Add New Magic Bread",
        style="Title.TLabel"
    )
    title_label.pack(pady=(50, 30))

    input_frame = ttk.Frame(parent, padding=(20, 10), style="Transparent.TFrame")
    input_frame.pack(pady=10, fill=tk.X, padx=150)

    input_config = [
        ("Bread Type (e.g. Chocolate Lava Croissant):", tk.StringVar()),
        ("Bread Name (e.g. Crispy):", tk.StringVar()),
        ("Bread Character (e.g. open):", tk.StringVar()),
        ("Bread Property (e.g. fire):", tk.StringVar()),
        ("Bread Ingredient (e.g. milk.etc):", tk.StringVar())
    ]
    input_entries = []  

    for idx, (label_text, var) in enumerate(input_config):
        label = ttk.Label(
            input_frame,
            text=label_text,
            style="Main.TLabel",
            anchor=tk.W
        )
        label.grid(row=idx, column=0, sticky=tk.W, padx=10, pady=12)

        entry = ttk.Entry(
            input_frame,
            textvariable=var,
            style="Main.TEntry",
            width=40
        )
        entry.grid(row=idx, column=1, padx=10, pady=12)
        input_entries.append(entry)

    def handle_submit():
        type_val = input_config[0][1].get().strip()
        name_val = input_config[1][1].get().strip()
        char_val = input_config[2][1].get().strip()
        prop_val = input_config[3][1].get().strip()
        ing_val = input_config[4][1].get().strip()

        if not all([type_val, name_val, char_val, prop_val, ing_val]):
            messagebox.showwarning(
                "Input Error",
                "All fields cannot be empty!\nPlease fill in every item."
            )
            for entry, var in zip(input_entries, [c[1] for c in input_config]):
                if not var.get().strip():
                    entry.focus()
                    break
            return

        import sys
        original_print = sys.stdout
        print_buffer = []

        class CapturePrint:
            def write(self, text):
                print_buffer.append(text)

            def flush(self):
                pass

        sys.stdout = CapturePrint()
        updated_items = create_item(
            items.copy(),
            bread_type=type_val,
            name=name_val,
            character=char_val,
            property=prop_val,
            ingredient=ing_val
        )
        sys.stdout = original_print 

        print_result = "".join(print_buffer)
        if "Created successfully" in print_result:
            items.clear()
            items.update(updated_items)
            messagebox.showinfo("Success", print_result.strip())
            from src.ui.tkinter.screens.selection_screen import show_selection_screen
            show_selection_screen(parent, items)
        elif "Maximum 4 items allowed" in print_result or "The warehouse is full" in print_result:
            messagebox.showwarning("Capacity Full", print_result.strip())
            from src.ui.tkinter.screens.selection_screen import show_selection_screen
            show_selection_screen(parent, items)
        else:
            messagebox.showerror("Error", "Failed to create bread!\nPlease try again.")
            for var in [c[1] for c in input_config]:
                var.set("")
            input_entries[0].focus()

    btn_frame = ttk.Frame(parent, padding=(20, 30), style="Transparent.TFrame")
    btn_frame.pack(pady=20)

    submit_btn = ttk.Button(
        btn_frame,
        text="Submit New Bread",
        style="Normal.TButton",
        command=handle_submit
    )
    submit_btn.grid(row=0, column=0, padx=20)

    def go_back_to_selection():
        from src.ui.tkinter.screens.selection_screen import show_selection_screen
        show_selection_screen(parent, items)

    back_btn = ttk.Button(
        btn_frame,
        text="Back to Management",
        style="Cancel.TButton",
        command=go_back_to_selection
    )
    back_btn.grid(row=0, column=1, padx=20)

    input_entries[0].focus()